package cn.edu.cug.cs.gtl.utils.impl;

import cn.edu.cug.cs.gtl.entity.Role;
import cn.edu.cug.cs.gtl.entity.User;
import cn.edu.cug.cs.gtl.utils.DatabaseUtil;
import cn.edu.cug.cs.gtl.utils.UserManager;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import java.util.List;

public class UserManagerImpl implements UserManager {
    DatabaseUtil databaseUtil = new DatabaseUtil();


    @Override
    public boolean register(String username, String password, String phone) {
        Connection con = databaseUtil.getConnection();
        // 密码MD5加密
        String encryptedPassword = encryptPassword(password);

        // 编写SQL注册语句
        String sql = "INSERT INTO public.user(username, password, phone) VALUES (?, ?, ?)";
        try (PreparedStatement preparedStatement = con.prepareStatement(sql)) {
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, encryptedPassword);
            preparedStatement.setString(3, phone);

            // 执行SQL语句
            int rowsAffected = preparedStatement.executeUpdate();

            // 检查是否插入成功
            return rowsAffected > 0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public User login(String username, String password) {
        Connection con = databaseUtil.getConnection();
        // 密码MD5加密
        String encryptedPassword = encryptPassword(password);
        User user = null;

        // 编写SQL查询语句，包括密码比较
        String sql = "SELECT * FROM public.user WHERE username = ? AND password = ?";
        try (PreparedStatement stmt = con.prepareStatement(sql)) {
            stmt.setString(1, username);
            stmt.setString(2, encryptedPassword);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    user = new User();
                    user.setUserID(rs.getInt("userid"));
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    user.setPhone(rs.getString("phone"));
                    user.setCreateTime(rs.getTimestamp("create_time"));
                    user.setLastLoginTime(rs.getTimestamp("last_login_time"));
                }
            }
        } catch (SQLException e) {
            // 更好地处理异常
            e.printStackTrace();
        }

        // 检查用户是否存在
        if (user == null) {
            System.out.println("用户不存在或密码错误");
        }

        return user;
    }


    @Override
    public void insertUser(User user) {

    }

    @Override
    public User getUser() {
        return null;
    }

    @Override
    public void insertRole(Role role) {

    }

    @Override
    public void updateRole(Role role, int id) {

    }

    @Override
    public List<Role> getList() {
        return null;
    }

    @Override
    public int getIdByName(String roleName) {
        return 0;
    }

    @Override
    public void removeRole(String roleName) {

    }

    // MD5加密方法
    private String encryptPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            byte[] encodedPassword = md.digest();
            return toHexString(encodedPassword);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 将字节数组转换为十六进制字符串
    private String toHexString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
